#!/usr/bin/env bash

set -e

if [[ $PWD == $HOME/src/gitlab.intr/* ]]
then
    JENKINS_URL="https://jenkins.corp1.majordomo.ru"
    JENKINS_USER="admin"
    JENKINS_PASSWORD="$(pass majordomo/public/jenkins.intr/admin)"
else
    JENKINS_URL="${JENKINS_URL:-https://jenkins.wugi.info}"
    JENKINS_USER="${JENKINS_USER:-admin}"
    JENKINS_PASSWORD="${JENKINS_PASSWORD:-$(pass show jenkins.wugi.info/token-admin)}"
fi

help_main()
{
    echo "\
Usage: connect COMMANDS ARGS...
Run COMMANDS with ARGS

COMMAND must be one of the sub-commands listed below:

   build
   stop

Report bugs to: go.wigust@gmail.com."
}

case "$1" in
    --help | -h)
        help_main
        exit 0
        ;;
    log)
        curl --silent "$JENKINS_URL"/job/"$(basename "$(dirname "$PWD")")"/job/"$(basename "$PWD")"/job/"$(git branch --show-current)"/lastBuild/consoleText
        ;;
    console)
        project="$(basename "$PWD")"
        group="$(basename "$(dirname "$PWD")")"
        "$BROWSER" "${JENKINS_URL}/job/${group}/job/${group}%252F${project}/job/$(git branch --show-current)/lastBuild/console"
        ;;
    build)
        curl --request POST --user "$JENKINS_USER:$JENKINS_PASSWORD" "$JENKINS_URL/job/$2/job/$3/build"
        ;;
    stop)
        data="$(cat << 'EOF'
// https://jenkins.intr/script

import java.util.ArrayList
import hudson.model.*;
import jenkins.model.Jenkins

// Remove everything which is currently queued
def q = Jenkins.instance.queue
for (queued in Jenkins.instance.queue.items) {
    q.cancel(queued.task)
}

// stop all the currently running jobs
for (job in Jenkins.instance.items) {
    stopJobs(job)
}

def stopJobs(job) {
    if (job in com.cloudbees.hudson.plugins.folder.Folder) {
        for (child in job.items) {
            stopJobs(child)
        }
    } else if (job in org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) {
        for (child in job.items) {
            stopJobs(child)
        }
    } else if (job in org.jenkinsci.plugins.workflow.job.WorkflowJob) {

        if (job.isBuilding()) {
            for (build in job.builds) {
                build.doKill()
            }
        }
    }
}
EOF
)"
        curl --user "$JENKINS_USER:$JENKINS_PASSWORD" "$JENKINS_URL/scriptText" --data-urlencode "script=$data"
        ;;
    *)
        help_main
        exit 0
        ;;
esac

# curl --request POST --user "$JENKINS_USER:$JENKINS_PASSWORD" \
# --data-urlencode json='{"parameter": [{"name":"CHEZMOI_APPLY", "value":"true"},{"name":"INVOKE_GUIX_PULL", "value":"true"}]}' \
# https://jenkins.wugi.info/job/wigust/job/dotfiles/job/master/build
